<template>
  <view
    class="container"
    :style="{ backgroundColor: settings.backgroundColor }"
  >
    <!-- 用户信息区域 -->
    <view class="user-info-section" @click="handleUserInfoClick">
      <view class="user-header">
        <image
          class="avatar"
          :src="
            userInfo.avatar ||
            'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
          "
          mode="aspectFill"
          @click.stop="previewAvatar"
        />
        <view class="user-details">
          <text
            class="username"
            :style="{ fontSize: settings.fontSize + 'px' }"
          >
            名称: {{ userInfo.username || "未登录" }}</text
          >
          <text
            class="points"
            :style="{ fontSize: settings.fontSize - 2 + 'px' }"
            >积分: {{ userInfo.points || 0 }}</text
          >
        </view>
      </view>
    </view>

    <!-- 余额展示与充值入口 -->
    <view class="balance-section" v-if="isLoggedIn">
      <view class="balance-info">
        <text class="balance-label">余额：</text>
        <text class="balance-amount">{{ userInfo.balance !== undefined ? userInfo.balance : '0.00' }}</text>
        <text class="balance-unit">&nbsp;元</text>
		<button class="recharge-btn" @click="goToBalance">充值</button>
      </view>
      
    </view>

    <!-- 功能菜单区域 -->
    <view class="menu-section">
      <view class="menu-item" @click="handleMenuClick('/pages/orders/orders')">
        <text class="menu-icon">📦</text>
        <text class="menu-text" :style="{ fontSize: settings.fontSize + 'px' }"
          >我的订单</text
        >
        <text class="arrow">></text>
      </view>

      <view
        class="menu-item"
        @click="handleMenuClick('/pages/points/exchange')"
      >
        <text class="menu-icon">🎁</text>
        <text class="menu-text" :style="{ fontSize: settings.fontSize + 'px' }"
          >积分兑换</text
        >
        <text class="arrow">></text>
      </view>

      <view class="menu-item" @click="handleMenuClick('/pages/favorite/index')">
        <text class="menu-icon">❤️</text>
        <text class="menu-text" :style="{ fontSize: settings.fontSize + 'px' }"
          >我的收藏</text
        >
        <text class="arrow">></text>
      </view>

      <view
        class="menu-item"
        @click="handleMenuClick('/pages/coupons/coupons')"
      >
        <text class="menu-icon">🎟️</text>
        <text class="menu-text" :style="{ fontSize: settings.fontSize + 'px' }"
          >优惠券</text
        >
        <text class="arrow">></text>
      </view>

      <view class="menu-item" @click="handleMenuClick('/pages/profile/edit')">
        <text class="menu-icon">✏️</text>
        <text class="menu-text" :style="{ fontSize: settings.fontSize + 'px' }"
          >编辑资料</text
        >
        <text class="arrow">></text>
      </view>

      <view class="menu-item" @click="navigateTo('/pages/settings/index')">
        <text class="menu-icon">⚙️</text>
        <text class="menu-text" :style="{ fontSize: settings.fontSize + 'px' }"
          >设置</text
        >
        <text class="arrow">></text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import http from '@/utils/request'
import { getUserAccount } from '@/api/user'

// 用户信息
const userInfo = reactive({
  id: 0,
  avatar: "",
  username: "",
  points: 0,
  email: "",
  phone: "",
  gender: "",
  balance: 0,
});

// 登录状态
const isLoggedIn = ref(false);

// 设置
const settings = reactive({
  fontSize: 16,
  backgroundColor: "#ffffff",
});

// 获取并刷新用户余额
const fetchUserBalance = async () => {
  if (!userInfo.id) return;
  try {
    const res = await getUserAccount(userInfo.id);
    if (res && res.data && typeof res.data.balance !== 'undefined') {
      userInfo.balance = res.data.balance;
    }
  } catch (e) {
    userInfo.balance = 0;
  }
};

// 页面显示时刷新数据
onShow(() => {
  checkLoginStatus();
  if (isLoggedIn.value && userInfo.id) {
    fetchUserBalance();
  }
});

// 监听设置变化
const handleSettingsChange = (newSettings: any) => {
  Object.assign(settings, newSettings);
};

// 预览头像
const previewAvatar = () => {
  if (!userInfo.avatar) return;

  uni.previewImage({
    urls: [userInfo.avatar],
    current: userInfo.avatar,
    indicator: "number",
    loop: false,
  });
};

// 检查登录状态
const checkLoginStatus = () => {
  const token = uni.getStorageSync("token");
  const storedUserInfo = uni.getStorageSync("userInfo");
  if (token && storedUserInfo) {
    isLoggedIn.value = true;
    Object.assign(userInfo, storedUserInfo);
  }
};

// 处理用户信息区域点击
const handleUserInfoClick = () => {
  if (!isLoggedIn.value) {
    uni.navigateTo({
      url: '/pages/login/index'
    });
  }
};

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    success: (res) => {
      if (res.confirm) {
        isLoggedIn.value = false;
        Object.assign(userInfo, {
          avatar: "",
          nickname: "",
          points: 0,
          email: "",
          phone: "",
        });
        // 清除本地存储的登录信息
        uni.removeStorageSync("token");
        uni.removeStorageSync("userInfo");
        // 跳转到个人中心页并刷新
        uni.switchTab({
          url: '/pages/my/my'
        });
      }
    },
  });
};

// 页面导航
const navigateTo = (url: string) => {
  uni.navigateTo({ url });
};

// 处理菜单点击
const handleMenuClick = (url: string) => {
  if (!isLoggedIn.value) {
    uni.navigateTo({
      url: '/pages/login/index'
    });
    return;
  }
  navigateTo(url);
};

// 跳转到余额充值页面
const goToBalance = () => {
  uni.navigateTo({ url: '/pages/my/balance' });
};

// 页面加载时检查登录状态
onMounted(() => {
  checkLoginStatus();
  if (isLoggedIn.value && userInfo.id) {
    fetchUserBalance();
  }
  const savedSettings = uni.getStorageSync("settings");
  if (savedSettings) {
    Object.assign(settings, savedSettings);
  }
  // 监听设置变化事件
  uni.$on("settingsChanged", handleSettingsChange);
  // 监听用户信息更新事件
  uni.$on("refreshUserInfo", () => {
    checkLoginStatus();
    if (isLoggedIn.value && userInfo.id) {
      fetchUserBalance();
    }
  });
  // 监听退出登录事件
  uni.$on("userLogout", () => {
    isLoggedIn.value = false;
    Object.assign(userInfo, {
      id: 0,
      avatar: "",
      username: "",
      points: 0,
      email: "",
      phone: "",
      gender: "",
      balance: 0,
    });
  });
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off("settingsChanged", handleSettingsChange);
  uni.$off("refreshUserInfo");
  uni.$off("userLogout");
});
</script>

<style>
.container {
  min-height: 100vh;
  padding: 20px 20px 0px 20px;
  transition: background-color 0.3s ease;
}

.user-info-section {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-info-section:active {
  opacity: 0.8;
}

.user-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px solid #f0f0f0;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: bold;
  margin-bottom: 8px;
  display: block;
}

.points {
  color: #666;
  display: block;
}

.login-btn,
.logout-btn {
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 14px;
  background-color: #007aff;
  color: white;
  border: none;
}

.logout-btn {
  background-color: #ff3b30;
}

.menu-section {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  margin-right: 15px;
  font-size: 20px;
}

.menu-text {
  flex: 1;
}

.arrow {
  color: #999;
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-image {
  width: 100px;
  height: 100px;
}

.balance-section {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.balance-info {
  display: flex;
  align-items: center;
}

.balance-label {
  font-weight: bold;
  margin-right: 10px;
}

.balance-amount {
  font-size: 18px;
  font-weight: bold;
}

.balance-unit {
	position: relative;
  color: #000;
  font-weight: 1000;
}

.recharge-btn {
  position: absolute;
  right: 30px;
  padding: 4px 20px;
  border-radius: 10px;
  font-size: 14px;
  background-color: #007aff;
  color: white;
  border: none;
}
</style>
